package vistas;

import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;

import modelo.LoteSimple.Estado;
import modelo.Mineral;
import modelo.vista.LoteSimpleView;
import modelo.vista.MineralLoteView;

import org.jdesktop.beansbinding.AutoBinding;
import org.jdesktop.beansbinding.AutoBinding.UpdateStrategy;
import org.jdesktop.beansbinding.BeanProperty;
import org.jdesktop.beansbinding.Bindings;
import org.jdesktop.swingbinding.JListBinding;
import org.jdesktop.swingbinding.JTableBinding;
import org.jdesktop.swingbinding.SwingBindings;

import controladores.AdministrateLotesControlador;
import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;


@SuppressWarnings("rawtypes")
public class AdministrateLotesSimplesVista extends JPanel implements AbstractVista<AdministrateLotesControlador> {

	private static final long serialVersionUID = 1L;
	private JTextField txtNumero;
	private JTextField txtArea;

	private JList listLotes;
	private JLabel lblNombre;
	private JTable jTableMinerales;
	private JButton btnAgregarMineral;
	private JButton btnRemoverMineral;
	private JTextField txtPorcentajMineral;
	private JComboBox cmbMinerales;
	private JButton btnBuscarLote;
	private JLabel lblBuscarLote;
	private JTextField txtBuscarLote;
	private JLabel lblBuscarMineral;
	private JButton btnModificarLote;
	private Mineral[] mineralesValues = Mineral.values();

	protected AdministrateLotesControlador controlador;
	private JTextField txtPropietarioDNI;
	private JLabel lblError;

	public AdministrateLotesSimplesVista() {
		super();
		initComponents();
	}

	public AdministrateLotesSimplesVista(AdministrateLotesControlador controlador) {
		super();
		this.controlador = controlador;
		initComponents();
	}

	public AdministrateLotesControlador getControlador() {
		return controlador;
	}

	public void setControlador(AdministrateLotesControlador controlador) {
		this.controlador = controlador;
	}

	@SuppressWarnings("unchecked")
	private void initComponents() {
		this.setLayout(null);
		this.setPreferredSize(new java.awt.Dimension(790, 413));
		listLotes = new JList();


		listLotes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		listLotes.setBounds(27, 174, 290, 66);
		add(listLotes);

		txtNumero = new JTextField();
		txtNumero.setBounds(184, 26, 231, 22);
		add(txtNumero);
		txtNumero.setColumns(10);

		lblNombre = new JLabel("Numero:");
		lblNombre.setBounds(27, 26, 109, 22);
		add(lblNombre);

		txtArea = new JTextField();
		txtArea.setColumns(10);
		txtArea.setBounds(184, 61, 231, 22);
		add(txtArea);

		JLabel lblSiembrainicio = new JLabel("Area de siembra:");
		lblSiembrainicio.setBounds(27, 64, 125, 16);
		add(lblSiembrainicio);

		JLabel lblSiembrafin = new JLabel("Proprietario:");
		lblSiembrafin.setBounds(27, 96, 126, 16);
		add(lblSiembrafin);
		lblSiembrafin.setText("Proprietario (DNI):");

		JButton btnAltaLoteSimple = new JButton(new ImageIcon(AdministrateLotesSimplesVista.class.getResource("/uiImages/add.png")));
		btnAltaLoteSimple.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(!txtArea.getText().equals("") && !txtNumero.getText().equals("") && controlador.getLotesView().size()>0){
					if(controlador.buscarPropietarioPorDNI(txtPropietarioDNI.getText())!=null){
						LoteSimpleView sl = new LoteSimpleView(Integer.parseInt(txtNumero.getText()), Estado.SIMPLE, 
								Float.parseFloat(txtArea.getText()), controlador.getLotesView().get(0).getMinerales(), 
								controlador.buscarPropietarioPorDNI(txtPropietarioDNI.getText()));
						controlador.altaLoteSimple(sl);
						listLotes.setSelectedIndex(0);
						txtArea.setText("");
						txtNumero.setText("");
						txtPorcentajMineral.setText("");
						txtPropietarioDNI.setText("");
						lblError.setVisible(false);
					}
					else{
						lblError.setVisible(true);
						lblError.setText("El propietario ingresado no existe");
					}
				}
				else{
					lblError.setVisible(true);
					lblError.setText("Debe completar todos los campos");
				}

			}
		});

		btnAltaLoteSimple.setHorizontalAlignment(SwingConstants.LEFT);

		btnAltaLoteSimple.setText("Agregar lote simple");
		btnAltaLoteSimple.setBounds(61, 342, 189, 40);
		add(btnAltaLoteSimple);

		JButton btnBajaLote = new JButton(new ImageIcon(AdministrateLotesSimplesVista.class.getResource("/uiImages/remove.png")));
		btnBajaLote.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				controlador.bajaLote();
				listLotes.setSelectedIndex(0);
				txtArea.setText("");
				txtNumero.setText("");
				txtPorcentajMineral.setText("");
				txtPropietarioDNI.setText("");
			}
		});

		btnBajaLote.setHorizontalAlignment(SwingConstants.LEFT);
		btnBajaLote.setText("Eliminar lote simple");
		btnBajaLote.setBounds(314, 342, 188, 40);
		add(btnBajaLote);

		txtPorcentajMineral = new JTextField();
		this.add(txtPorcentajMineral);
		txtPorcentajMineral.setBounds(689, 163, 59, 23);

		btnModificarLote = new JButton();
		this.add(btnModificarLote);
		btnModificarLote.setText("Modificar lote simple");
		btnModificarLote.setBounds(556, 342, 185, 40);
		btnModificarLote.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				controlador.modificarLoteSimple();
				listLotes.setSelectedIndex(0);
				txtArea.setText("");
				txtNumero.setText("");
				txtPorcentajMineral.setText("");
				txtPropietarioDNI.setText("");
			}
		});

		lblBuscarMineral = new JLabel();
		this.add(lblBuscarMineral);
		lblBuscarMineral.setText("Mineral:");
		lblBuscarMineral.setBounds(470, 166, 61, 16);

		txtBuscarLote = new JTextField();
		txtBuscarLote.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent arg0) {
				String t = txtBuscarLote.getText().substring(0,txtBuscarLote.getText().length()-1);
				if(arg0.getKeyChar() != '1' && arg0.getKeyChar() != '2' && arg0.getKeyChar() != '3' && arg0.getKeyChar() != '4' && arg0.getKeyChar() != '5' && arg0.getKeyChar() != '6' && arg0.getKeyChar() != '7' && arg0.getKeyChar() != '8' && arg0.getKeyChar() != '9' && arg0.getKeyChar() != '0'  ){
					t.replace(arg0.getKeyChar(),'1');
					txtBuscarLote.setText(t);
				}
			}
		});

		this.add(txtBuscarLote);
		txtBuscarLote.setBounds(139, 251, 84, 23);

		lblBuscarLote = new JLabel();
		this.add(lblBuscarLote);
		lblBuscarLote.setText("Buscar lote:");
		lblBuscarLote.setBounds(39, 254, 97, 16);

		btnBuscarLote = new JButton();
		this.add(btnBuscarLote);
		btnBuscarLote.setText("Buscar");
		btnBuscarLote.setBounds(233, 251, 84, 23);
		btnBuscarLote.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(!txtBuscarLote.getText().equals("")){
				String nombre = txtBuscarLote.getText();
				LoteSimpleView loteBuscado = controlador.buscarConNumero(Integer.parseInt(nombre));
					if(loteBuscado != null){
						controlador.getLotesView().remove(0);
						controlador.getLotesView().add(loteBuscado);
						listLotes.setSelectedIndex(0);
						txtBuscarLote.setText("");
						lblError.setVisible(false);
					}
					else{
						txtBuscarLote.setText("No se encontro Lote");
					}
				}
				else{
					lblError.setVisible(true);
					lblError.setText("Debe ingresar un Numero de Lote");
				}
			}
		});


		cmbMinerales = new JComboBox();
		cmbMinerales.setModel(new DefaultComboBoxModel(mineralesValues));
		this.add(cmbMinerales);
		cmbMinerales.setBounds(543, 163, 134, 23);

		listLotes.setSelectedIndex(0);

		jTableMinerales = new JTable();
		jTableMinerales.setBounds(470, 18, 281, 133);
		add(jTableMinerales);

		btnAgregarMineral = new JButton((Icon) null);
		btnAgregarMineral.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				MineralLoteView mineralView = new MineralLoteView(mineralesValues[cmbMinerales.getSelectedIndex()], 
						Float.parseFloat(txtPorcentajMineral.getText()));
				controlador.agregarLoteMineral(mineralView);
			}
		});
		btnAgregarMineral.setText("Agregar Mineral");
		btnAgregarMineral.setHorizontalAlignment(SwingConstants.LEFT);
		btnAgregarMineral.setBounds(614, 204, 134, 30);
		add(btnAgregarMineral);

		btnRemoverMineral = new JButton((Icon) null);
		btnRemoverMineral.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				controlador.eliminarLoteMineral(mineralesValues[cmbMinerales.getSelectedIndex()]);
			}
		});
		btnRemoverMineral.setText("Remover Mineral");
		btnRemoverMineral.setHorizontalAlignment(SwingConstants.LEFT);
		btnRemoverMineral.setBounds(614, 247, 136, 34);
		add(btnRemoverMineral);

		txtPropietarioDNI = new JTextField();
		txtPropietarioDNI.setBounds(184, 94, 231, 22);
		add(txtPropietarioDNI);
		txtPropietarioDNI.setColumns(10);

		lblError = new JLabel("");
		lblError.setForeground(Color.RED);
		lblError.setVisible(false);
		lblError.setBounds(60, 299, 313, 14);
		add(lblError);
		initDataBindings();

	}



	class MineralEditor extends DefaultCellEditor {
		private static final long serialVersionUID = 1L;
		@SuppressWarnings("unchecked")
		public MineralEditor(Object[] items) {
			super(new JComboBox(items));
		}
	}
	protected void initDataBindings() {
		BeanProperty<AdministrateLotesControlador, List<LoteSimpleView>> administrateLotesControladorBeanProperty = BeanProperty.create("lotesView");
		JListBinding<LoteSimpleView, AdministrateLotesControlador, JList> jListBinding = SwingBindings.createJListBinding(UpdateStrategy.READ, controlador, administrateLotesControladorBeanProperty, listLotes);
		//
		BeanProperty<LoteSimpleView, Integer> loteBeanProperty = BeanProperty.create("nroLote");
		jListBinding.setDetailBinding(loteBeanProperty);
		//
		jListBinding.bind();
		//
		BeanProperty<JList, Integer> jListBeanProperty = BeanProperty.create("selectedElement.nroLote");
		BeanProperty<JTextField, String> jTextFieldBeanProperty = BeanProperty.create("text");
		AutoBinding<JList, Integer, JTextField, String> autoBinding = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, listLotes, jListBeanProperty, txtNumero, jTextFieldBeanProperty);
		autoBinding.bind();
		//
		BeanProperty<JList, Float> jListBeanProperty_1 = BeanProperty.create("selectedElement.areaSiembra");
		BeanProperty<JTextField, String> jTextFieldBeanProperty_1 = BeanProperty.create("text");
		AutoBinding<JList, Float, JTextField, String> autoBinding_1 = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, listLotes, jListBeanProperty_1, txtArea, jTextFieldBeanProperty_1);
		autoBinding_1.bind();
		//
		BeanProperty<JList, String> jListBeanProperty_2 = BeanProperty.create("selectedElement.propretario.dni");
		BeanProperty<JTextField, String> jTextFieldBeanProperty_3 = BeanProperty.create("text");
		AutoBinding<JList, String, JTextField, String> autoBinding_3 = Bindings.createAutoBinding(UpdateStrategy.READ_WRITE, listLotes, jListBeanProperty_2, txtPropietarioDNI, jTextFieldBeanProperty_3, "dniBindingNewProperty");
		autoBinding_3.bind();
		//
		BeanProperty<JList, List<MineralLoteView>> jListBeanProperty_3 = BeanProperty.create("selectedElement.minerales");
		JTableBinding<MineralLoteView, JList, JTable> jTableBinding = SwingBindings.createJTableBinding(UpdateStrategy.READ_WRITE, listLotes, jListBeanProperty_3, jTableMinerales);
		//
		BeanProperty<MineralLoteView, Mineral> mineralPorcentajeBeanProperty = BeanProperty.create("mineral");
		jTableBinding.addColumnBinding(mineralPorcentajeBeanProperty).setColumnName("Mineral");
		//
		BeanProperty<MineralLoteView, Float> mineralPorcentajeBeanProperty_1 = BeanProperty.create("porcentaje");
		jTableBinding.addColumnBinding(mineralPorcentajeBeanProperty_1).setColumnName("Porcentaje");
		//
		jTableBinding.bind();
	}
}



